package cn.gx.learn.security_boot_jwt_websocket.affairs.ws.listener;

import cn.gx.learn.security_boot_jwt_websocket.affairs.ws.event.WsEvent;
import cn.gx.learn.security_boot_jwt_websocket.aop.dal.date.Log;
import cn.gx.learn.security_boot_jwt_websocket.aop.service.LogService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

@Component
@Async
@Slf4j
public class WsListener {

    @Autowired
    private LogService logService;

    @Resource(name = "threadpool")
    private ThreadPoolExecutor logthreadpool;

    @EventListener(value = WsEvent.class)
    public void wsListener(WsEvent wsConectionEvent){
        Log object= (Log) wsConectionEvent.getSource();
        log.info("WsListener接收到了消息 ： "+object);

        logthreadpool.submit(()->{
            long startTime = System.currentTimeMillis();
            try {
                logService.save(object);
                logService.logTaskCompletion(logthreadpool,startTime,true,null);
            }
            catch (Exception e) {
                logService.logTaskCompletion(logthreadpool,startTime,false,e);
                throw new RuntimeException(e);
            }
        });
    }
}
